/**
 * 封装请求方法
 * */
import axios from 'axios'
// import { baseUrl } from './global'
import { message } from '@/utils/message'
import Cookies from 'js-cookie'
import router from '@/router'
// import store from '@/store'
import BASEURL from './baseUrl'
const service = axios.create({
  baseURL: BASEURL,
  // 请求时间
  timeout: 30000,
  headers: { 'Content-Type': 'application/json; charset=utf-8' }
})
service.withCredentials = true
service.interceptors.request.use(config => {
  let token = Cookies.get('token')
  let authorization = Cookies.get('authorization')
  config.headers['token'] = token
  config.headers['Authorization'] = authorization
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
service.interceptors.response.use((response) => {
  Cookies.set('authorization', response.headers.authorization)
  if (response && response.data.code === 200) {
    if (response.config.method === 'post' || response.config.method === 'delete' || response.config.method === 'put') {
      if (response.config.url.indexOf('auth/login') === -1) {
        message({
          type: 'success',
          message: response.data.message
        })
      }
    }
    return response.data
  } else if (response.data.code === 2002) {
    message({
      type: 'error',
      message: response.data.message
    })
    Cookies.remove('authorization')
    Cookies.remove('token')
    router.replace('/login')
  } else if (!(response.data.code === 200)) {
    message({
      type: 'error',
      message: response.data.message || response.data.msg
    })
  } else if (response.data.code === 500) {
    message({
      type: 'error',
      message: response.data.message || response.data.msg
    })
  } else {
    message({
      type: 'error',
      message: response.data.message
    })
  }
  return response.data
}, (err) => {
  // loading.close()
  message({
    type: 'error',
    message: err.message || '网络异常'
  })
})

/**
 * method  方法
 * url     请求地址
 * data    数据
 * show    控制如何传参数 true在url后面
 * */
export default function (val) {
  const url = val.url
  const method = val.method.toLocaleLowerCase()
  const data = val.data
  const show = val.show || false
  if (method === 'get') {
    if (show) {
      return service.get(`${url}/${data.id}`)
    } else {
      return service.get(url, { params: data })
    }
  } else if (method === 'post') {
    return service.post(url, data)
  } else if (method === 'put') {
    return service.put(`${url}/${data.id}`, data)
  } else if (method === 'delete') {
    if (show) {
      return service.delete(`${url}/${data.id}`)
    } else {
      return service.delete(`${url}`, { params: data })
      // return service.delete(`${url}/?id=${data.id}`)
    }
  } else {
    console.log('......测测试')
  }
}
